<template>
  <div class="basic-wrap">
    <div class="button-wrap">
      <a-space>
        <a-button type="primary" @click="openAddAsset = true">新增</a-button>
      </a-space>
      <div class="right-button-wrap">
        <a-input v-model:value="keyword" placeholder="关键词查询" style="width:160px;margin-right:8px">
          <template #prefix>
            <SearchOutlined style="color:#666"/>
          </template>
        </a-input>
        <a-button type="primary"  @click="list">查询</a-button>
      </div>
    </div>
    <div class="table-wrap">
      <a-table size="middle" :dataSource="dataSource" :columns="columns" :loading="loading">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDetail(record)"
            >
              查看
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <!--    <add-asset :open="openAddAsset" @handleSubmit="handleSubmit"></add-asset>-->
    <a-modal
      v-model:visible="openAddAsset"
      title="新增客户"
      width="60%"
      @ok="handleSubmit"
    >
      <a-form
        ref="formRef"
        style="margin-top: 24px"
        :model="formState"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 17 }"
        autocomplete="off"
      >
        <a-form-item
          label="客户名称"
          name="clientName"
          :rules="[
            { required: true, message: 'Please input your clientName!' },
          ]"
        >
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.clientName"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <FloorPosition :clientId="curClientId" :open="openPosition" @close="closeFloorPosition" :key="refreshKey"></FloorPosition>
<!--    <Test :clientId="curClientId" :open="openPosition" @close="closeFloorPosition" :key="refreshKey"></Test>-->

  </div>
</template>

<script lang="ts" setup>
import { ref, unref, computed, onMounted, reactive, watch } from 'vue';
import type { FormInstance, UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import type {AssetPageVo, AssetBo, ClientBo, PositionVo, ClientVo} from '#/api/common';
import dayjs from 'dayjs';
import {
  addAssetApi,
  pageAssetApi,
  listClientApi,
  addClientApi,
  deletePositionApi,
  delClientApi
} from '#/api';
import { useAccessStore } from '@vben/stores';
import {SearchOutlined} from "@ant-design/icons-vue";

import FloorPosition from "./components/FloorPosition.vue"
import Test from "./components/Test.vue"

const keyword = ref<string>('');
const assetType = ref<string>('');
const refreshKey = ref<string>('');
const dataSource = ref<ClientVo[]>([]);
type RangeValue = [Dayjs, Dayjs];
const searchDate = ref<RangeValue>();
const dateValue = ref<Dayjs>();
const loading = ref(false);
const open = ref(false);
const openFiles = ref(false);
const formRef = ref<FormInstance>();
const fileList = ref([]);
const openAddAsset = ref(false);
const openPosition = ref<Boolean>(false);

const accessStore = useAccessStore();

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const curClientId = ref('');

let fileListData = ref<ContractFileDto[]>([]);
let currentContractId = ref<string>('');

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 15,
  size: '',
  showSizeChanger: false,
  showQuickJumper: false,
});
const pageParam = computed(() => ({
  query: {
    keyword: unref<string>(keyword),
    assetType: unref<string>(assetType),
  },
  current: pagination.value?.current,
  size: pagination.value?.pageSize,
}));

const columns = [
  {
    title: '客户ID',
    dataIndex: 'id',
    key: 'id',
    width: 200,
    align: 'center',
  },
  {
    title: '客户名称',
    dataIndex: 'clientName',
    key: 'clientName',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 250,
    align: 'center',
  },
];

onMounted(() => {
  list();
});

watch(dateValue, (newValue, oldValue) => {
  console.log(`新值: ${newValue}, 旧值: ${oldValue}`);
  formState.contractDate = dayjs(newValue).format('YYYY-MM-DD');
});

let formState = reactive<ClientBo>({
  clientName: '',
});

const handleSubmit = () => {
  const _this = this;
  formRef.value
    ?.validateFields()
    .then(() => {
      addClientApi(formState).then(() => {
        message.success('添加成功');
        list();
        openAddAsset.value = false;
      });
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};
async function list() {
  loading.value = true;
  const res = await listClientApi();
  dataSource.value = res;
  loading.value = false;
}


const handleAddSubmit = () => {
  formRef.value
    ?.validateFields()
    .then(() => {
      // formState.files = fileResultList.value;
      // console.log('fileResultList', fileResultList);
      console.log('formState', formState);
      addClientApi(formState).then(() => {
        message.success('新增成功');
      });
      // addUser(formState).then(() => {
      //   message.success('添加成功')
      //   open.value = false
      //   list()
      // })
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};

const handleDetail = (record) =>{
// openPosition.value = true
  console.log('here')
  refreshKey.value = Math.random();
  curClientId.value = record.id
  openPosition.value = true
}
const handlePositionSubmit = () =>{
  // openPosition.value = false
}

const closeFloorPosition = () => {
  console.log('close')
  openPosition.value = false
}

const handleDelete = async (record:ClientVo) => {
  loading.value = true
  await delClientApi({id: record.id}).finally(() => {
    loading.value = false
  })
  message.success("删除成功")
  await list()
}
</script>
<style lang="less">
.basic-wrap {
  margin: 0 16px;
}

.button-wrap {
  margin: 16px 0;
  display: flex;
}

.right-button-wrap {
  margin-left: auto;
}

</style>
